package com.it.shiro.config;

import com.it.shiro.pojo.UserBean;
import com.it.shiro.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * ClassName:MyRealm
 * Package:com.it.shiro.config
 * Description: 数据
 *
 * @date:2022/3/30 11:19
 * @author:动力节点
 */
@Configuration
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(MyRealm.class);
    /**
     *
     * @param principalCollection
     * @return  授权  访问权限是出发授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("entered MyRealm doGetAuthorizationInfo method");
        //获得当前的用户
        UserBean user = (UserBean) principalCollection.asList().get(0);
        //简单的授权信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //需要綁定角色，資源
        simpleAuthorizationInfo.addRoles(user.getUserRoles());
        simpleAuthorizationInfo.addStringPermissions(user.getUserPerms());

        return simpleAuthorizationInfo;
    }


    /**
     *
     * @param authenticationToken
     * @return  认证  登录是触发认证判断
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info(">>>entered MyRealm doGetAuthenticationInfo method");
        //获取当前用户
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //获得数据库中的用户，来跟当前地用户进行比对，认证。
        String username = userToken.getUsername();
        //当前用户和数据库中的用户进行密码匹配
        UserBean userBean = userService.queryUserName(username);
        //如果没有查到,表示没有这个用户
        if (userBean == null){
            return null; //会抛出UnknownAccountException异常
        }
        // 3、当前用户和数据库中的用户进行密码设置，shiro自带密码比对
        ByteSource salt = ByteSource.Util.bytes("salt");
        //返回AuthenticationInfo，完成了认证流程
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(userBean,userBean.getUserPass(),salt,"MyRealm");
        return simpleAuthenticationInfo;
    }
}
